import axios from 'axios'
import { MessageBox } from 'element-ui'
import  components  from '../register.js'
import { ERR_OK } from 'api/config.js'
import { BASE_URL } from 'api/config.js'
import store from '@/store'
import { getToken, setToken, setUserInfo } from '@/utils/cache.js'

const Message = components.Message
const service = axios.create({
  baseURL: BASE_URL,
  timeout: 10000
})

// 请求拦截  往请求头添加token
service.interceptors.request.use(
  config => {
      if (store.getters.token) {
          config.headers['Authorization'] = getToken()
      }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

//响应拦截
service.interceptors.response.use(
  response => {
    let {status, data} = response
    if (status !== 200) {
      Message.error('网络异常，请刷新或者重试!')
      return Promise.reject('网络异常!')
    }
    if (data.code !== ERR_OK && data.code != 403) {
      Message.error(data.msg || '接口请求异常，请重试!')
      return Promise.reject(data.msg || '接口异常!')
    }
    if (data.code == 403) {
      setToken(null)
      setUserInfo(null)
      MessageBox.confirm('你的登录状态已失效，你可以选择重新登陆或留在此页面', '登录状态失效', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href = '/home'
      })
      return Promise.resolve(data)
    }
    return Promise.resolve(data)
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
